<template>
  <view class="login-page">
    <!-- 自定义状态栏 -->
    <view class="status-bar safe-area-inset-top"></view>
    
    <!-- 返回按钮 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <text class="back-icon">←</text>
      </view>
    </view>
    
    <!-- 登录头部 -->
    <view class="login-header">
      <view class="logo-container">
        <view class="logo">
          <text class="logo-icon">🎮</text>
        </view>
        <text class="app-name">星际网咖</text>
      </view>
      
      <view class="welcome-text">
        <text class="welcome-title">欢迎来到星际网咖</text>
        <text class="welcome-subtitle">随时随地，轻松预约座位</text>
      </view>
    </view>
    
    <!-- 登录表单 -->
    <view class="login-form">
      <text class="form-title">登录 / 注册</text>
      
      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view 
          class="tab-item" 
          :class="{ active: loginType === 'phone' }"
          @click="switchLoginType('phone')"
        >
          <text class="tab-text">手机登录</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: loginType === 'wechat' }"
          @click="switchLoginType('wechat')"
        >
          <text class="tab-text">微信登录</text>
        </view>
      </view>
      
      <!-- 手机号登录 -->
      <view v-if="loginType === 'phone'" class="phone-login">
        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ focused: phoneFocused, error: phoneError }">
            <text class="input-prefix">+86</text>
            <input 
              class="input-field" 
              type="number" 
              placeholder="请输入手机号" 
              v-model="phone"
              maxlength="11"
              @focus="phoneFocused = true"
              @blur="phoneFocused = false"
              @input="validatePhone"
            />
            <view v-if="phone" class="input-clear" @click="clearPhone">
              <text class="clear-icon">×</text>
            </view>
          </view>
          <text v-if="phoneError" class="error-text">{{ phoneError }}</text>
        </view>
        
        <!-- 验证码输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ focused: codeFocused }">
            <input 
              class="input-field" 
              type="number" 
              placeholder="请输入验证码" 
              v-model="smsCode"
              maxlength="6"
              @focus="codeFocused = true"
              @blur="codeFocused = false"
            />
            <button 
              class="code-btn" 
              :disabled="codeDisabled" 
              :class="{ disabled: codeDisabled }"
              @click="sendCode"
            >
              {{ codeText }}
            </button>
          </view>
        </view>
        
        <!-- 登录按钮 -->
        <button 
          class="login-btn" 
          :disabled="!canLogin" 
          :class="{ disabled: !canLogin, loading: userStore.loginLoading }"
          @click="handlePhoneLogin"
        >
          <view v-if="userStore.loginLoading" class="loading-icon"></view>
          <text class="btn-text">{{ userStore.loginLoading ? '登录中...' : '登录' }}</text>
        </button>
      </view>
      
      <!-- 微信登录 -->
      <view v-else class="wechat-login">
        <view class="wechat-info">
          <text class="wechat-title">微信一键登录</text>
          <text class="wechat-desc">使用微信账号快速登录，享受便捷服务</text>
        </view>
        
        <button 
          class="wechat-btn" 
          :class="{ loading: userStore.loginLoading }"
          @click="handleWechatLogin"
        >
          <view v-if="userStore.loginLoading" class="loading-icon"></view>
          <text v-else class="wechat-icon">💬</text>
          <text class="btn-text">{{ userStore.loginLoading ? '登录中...' : '微信登录' }}</text>
        </button>
      </view>
      
      <!-- 分割线 -->
      <view class="divider">
        <view class="divider-line"></view>
        <text class="divider-text">或</text>
        <view class="divider-line"></view>
      </view>
      
      <!-- 游客模式 -->
      <view class="guest-mode" @click="guestMode">
        <text class="guest-text">游客模式浏览</text>
        <text class="guest-desc">无需登录，体验基础功能</text>
      </view>
      
      <!-- 用户协议 -->
      <view class="agreement">
        <checkbox-group @change="onAgreementChange">
          <label class="agreement-item">
            <checkbox :checked="agreed" color="#007AFF" />
            <text class="agreement-text">
              我已阅读并同意
              <text class="agreement-link" @click.stop="showAgreement">《用户协议》</text>
              和
              <text class="agreement-link" @click.stop="showPrivacy">《隐私政策》</text>
            </text>
          </label>
        </checkbox-group>
      </view>
    </view>
    
    <!-- 底部装饰 -->
    <view class="login-footer">
      <text class="footer-text">星际网咖 · 您的游戏伙伴</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { validatePhone as validatePhoneUtil, showError, showSuccess } from '@/utils/common'

const userStore = useUserStore()

// 响应式数据
const loginType = ref('phone')
const phone = ref('')
const smsCode = ref('')
const agreed = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)

// 输入框焦点状态
const phoneFocused = ref(false)
const codeFocused = ref(false)

// 错误状态
const phoneError = ref('')

// 计算属性
const canLogin = computed(() => {
  if (loginType.value === 'phone') {
    return validatePhoneUtil(phone.value) && smsCode.value.length === 6 && agreed.value
  }
  return agreed.value
})

const codeDisabled = computed(() => {
  return !validatePhoneUtil(phone.value) || countdown.value > 0
})

const codeText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s` : '获取验证码'
})

// 方法
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.switchTab({
      url: '/pages/index/index'
    })
  }
}

const switchLoginType = (type) => {
  loginType.value = type
  // 清空表单
  phone.value = ''
  smsCode.value = ''
  phoneError.value = ''
}

const validatePhone = () => {
  if (phone.value && !validatePhoneUtil(phone.value)) {
    phoneError.value = '请输入正确的手机号'
  } else {
    phoneError.value = ''
  }
}

const clearPhone = () => {
  phone.value = ''
  phoneError.value = ''
}

const sendCode = async () => {
  if (!validatePhoneUtil(phone.value)) {
    phoneError.value = '请输入正确的手机号'
    return
  }
  
  if (!agreed.value) {
    showError('请先同意用户协议和隐私政策')
    return
  }
  
  try {
    const result = await userStore.sendSmsCode(phone.value)
    if (result.success) {
      showSuccess('验证码已发送')
      startCountdown()
    } else {
      showError(result.message || '发送失败')
    }
  } catch (error) {
    showError('发送失败，请重试')
  }
}

const startCountdown = () => {
  countdown.value = 60
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value)
    }
  }, 1000)
}

const handlePhoneLogin = async () => {
  if (!canLogin.value) return
  
  try {
    const result = await userStore.phoneLogin(phone.value, smsCode.value)
    if (result.success) {
      showSuccess('登录成功')
      // 返回上一页或跳转到首页
      setTimeout(() => {
        const pages = getCurrentPages()
        if (pages.length > 1) {
          uni.navigateBack()
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }, 1000)
    } else {
      showError(result.message || '登录失败')
    }
  } catch (error) {
    showError('登录失败，请重试')
  }
}

const handleWechatLogin = async () => {
  if (!agreed.value) {
    showError('请先同意用户协议和隐私政策')
    return
  }
  
  try {
    const result = await userStore.wechatLogin()
    if (result.success) {
      showSuccess('登录成功')
      setTimeout(() => {
        const pages = getCurrentPages()
        if (pages.length > 1) {
          uni.navigateBack()
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }, 1000)
    } else {
      showError(result.message || '微信登录失败')
    }
  } catch (error) {
    showError('微信登录失败，请重试')
  }
}

const guestMode = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

const onAgreementChange = (e) => {
  agreed.value = e.detail.value.length > 0
}

const showAgreement = () => {
  // uni.navigateTo({
  //   url: '/pages/common/webview?url=https://example.com/agreement&title=用户协议'
  // })
  alert('用户协议')
}

const showPrivacy = () => {
  // uni.navigateTo({
  //   url: '/pages/common/webview?url=https://example.com/privacy&title=隐私政策'
  // })
  alert('隐私政策')
}

// 生命周期
onMounted(() => {
  // 如果已经登录，直接返回
  if (userStore.isLoggedIn) {
    uni.switchTab({
      url: '/pages/index/index'
    })
  }
})
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 44px;
}

.nav-bar {
  padding: 8px 16px;
}

.nav-back {
  width: 36px;
  height: 36px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;

  .back-icon {
    font-size: 20px;
    color: white;
    font-weight: bold;
  }
}

.login-header {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  padding: 20px;
  min-height: 200px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.logo {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  backdrop-filter: blur(10px);
}

.logo-icon {
  font-size: 36px;
}

.app-name {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.welcome-text {
  text-align: center;
}

.welcome-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
  display: block;
}

.welcome-subtitle {
  font-size: 14px;
  opacity: 0.9;
}

.login-form {
  background: white;
  border-radius: 24px 24px 0 0;
  padding: 32px 24px 40px;
  flex-shrink: 0;
  min-height: 60vh;
}

.form-title {
  font-size: 24px;
  font-weight: bold;
  color: var(--color-text-primary);
  text-align: center;
  margin-bottom: 24px;
  display: block;
}

.login-tabs {
  display: flex;
  background: var(--color-background);
  border-radius: var(--radius-lg);
  padding: 4px;
  margin-bottom: 24px;
}

.tab-item {
  flex: 1;
  padding: 12px;
  text-align: center;
  border-radius: var(--radius-md);
  transition: all var(--transition-normal);

  &.active {
    background: white;
    box-shadow: var(--shadow-sm);
  }

  .tab-text {
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text-primary);
  }
}

.phone-login,
.wechat-login {
  margin-bottom: 24px;
}

.input-group {
  margin-bottom: 20px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: var(--color-background);
  border: 2px solid transparent;
  border-radius: var(--radius-lg);
  padding: 0 16px;
  height: 56px;
  transition: all var(--transition-normal);

  &.focused {
    border-color: var(--color-primary);
    background: white;
    box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.1);
  }

  &.error {
    border-color: var(--color-error);
    background: rgba(255, 59, 48, 0.05);
  }
}

.input-prefix {
  color: var(--color-text-secondary);
  margin-right: 12px;
  font-size: 16px;
  font-weight: 500;
}

.input-field {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 16px;
  color: var(--color-text-primary);
  outline: none;

  &::placeholder {
    color: var(--color-text-tertiary);
  }
}

.input-clear {
  width: 20px;
  height: 20px;
  background: var(--color-text-tertiary);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;

  .clear-icon {
    font-size: 14px;
    color: white;
  }
}

.code-btn {
  background: transparent;
  border: none;
  color: var(--color-primary);
  font-size: 14px;
  font-weight: 500;
  padding: 8px 12px;
  border-radius: var(--radius-md);
  transition: all var(--transition-normal);

  &:not(.disabled):active {
    background: rgba(0, 122, 255, 0.1);
  }

  &.disabled {
    color: var(--color-text-tertiary);
  }
}

.error-text {
  font-size: 12px;
  color: var(--color-error);
  margin-top: 8px;
  margin-left: 16px;
}

.login-btn,
.wechat-btn {
  width: 100%;
  height: 56px;
  border: none;
  border-radius: var(--radius-lg);
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all var(--transition-normal);

  &:not(.disabled):not(.loading):active {
    transform: scale(0.98);
  }
}

.login-btn {
  background: var(--color-primary);
  color: white;
  box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);

  &.disabled {
    background: var(--color-text-tertiary);
    box-shadow: none;
  }
}

.wechat-btn {
  background: #07C160;
  color: white;
  box-shadow: 0 4px 16px rgba(7, 193, 96, 0.3);
}

.wechat-info {
  text-align: center;
  margin-bottom: 24px;
}

.wechat-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 8px;
}

.wechat-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.wechat-icon {
  font-size: 20px;
}

.loading-icon {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-text {
  color: inherit;
}

.divider {
  display: flex;
  align-items: center;
  margin: 24px 0;
}

.divider-line {
  flex: 1;
  height: 1px;
  background: var(--color-border);
}

.divider-text {
  margin: 0 16px;
  color: var(--color-text-secondary);
  font-size: 14px;
}

.guest-mode {
  text-align: center;
  padding: 16px;
  background: rgba(0, 122, 255, 0.05);
  border-radius: var(--radius-lg);
  margin-bottom: 24px;
  transition: all var(--transition-normal);

  &:active {
    background: rgba(0, 122, 255, 0.1);
  }
}

.guest-text {
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 500;
  display: block;
  margin-bottom: 4px;
}

.guest-desc {
  color: var(--color-text-secondary);
  font-size: 12px;
}

.agreement {
  margin-top: 20px;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.agreement-text {
  font-size: 12px;
  color: var(--color-text-secondary);
  line-height: 1.5;
  flex: 1;
}

.agreement-link {
  color: var(--color-primary);
  text-decoration: underline;
}

.login-footer {
  text-align: center;
  padding: 20px;
  color: rgba(255, 255, 255, 0.8);
}

.footer-text {
  font-size: 12px;
}

// 响应式适配
@media (max-height: 667px) {
  .login-header {
    min-height: 120px;
    padding: 16px;
  }

  .logo {
    width: 60px;
    height: 60px;
    border-radius: 30px;
  }

  .logo-icon {
    font-size: 28px;
  }

  .app-name {
    font-size: 20px;
  }

  .welcome-title {
    font-size: 18px;
  }

  .form-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
}
</style>
